package com.moco.sso.service;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaStorage;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson2.JSONObject;
import com.moco.core.constant.SecurityConstants;
import com.moco.core.domain.R;
import com.moco.core.exception.ServiceException;
import com.moco.core.model.LoginUser;
import com.moco.core.util.StringUtils;
import com.moco.core.util.ip.IpUtils;
import com.moco.system.api.RemoteUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 */
@RefreshScope
@Component
public class LoginService {

    @Value("${shop.brand}")
    private String shopBrand;

    @Resource
    private RemoteUserService remoteUserService;

    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * @return LoginUser
     */
    public LoginUser login(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username);
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        //enable=0停用,1正常
        if (userInfo.getSysUser().getEnable() == 0) {
            throw new ServiceException("您的账号：" + username + " 已停用");
        }
        //DeleteStatus=0正常,1删除
        if (userInfo.getSysUser().getDeleteStatus() == 1) {
            throw new ServiceException("您的账号：" + username + " 已被删除");
        }
        if (!StrUtil.equalsIgnoreCase(userInfo.getSysUser().getPassword(), SecureUtil.md5(password))) {
            throw new ServiceException("用户名或密码错误");
        }
        JSONObject shopIdBrandMap = JSONObject.parse(shopBrand);
        Integer brandId = (Integer) shopIdBrandMap.get(userInfo.getSysUser().getShopId());
        userInfo.getSysUser().setBrandId(String.valueOf(brandId));

        //设值
        userInfo.setShopId(userInfo.getSysUser().getShopId());
        userInfo.setStoreId(userInfo.getSysUser().getStoreId());
        userInfo.setUserArea(userInfo.getSysUser().getUserArea());
        userInfo.setUserId(userInfo.getSysUser().getUserId());
        userInfo.setUserName(userInfo.getSysUser().getUserName());
        userInfo.setIpaddr(IpUtils.getIpAddr());

        //SaToken登陆
        StpUtil.login(userInfo.getUserId());
        String token = StpUtil.getTokenValue();
        userInfo.setToken(token);

        //放入Request,在一次请求范围内: 存值、取值。数据在请求结束后失效。
        SaStorage storage = SaHolder.getStorage();
        storage.set(SecurityConstants.LOGIN_USER, userInfo);
        storage.set(SecurityConstants.USER_KEY, userInfo.getUserId());
        //放入Session
        StpUtil.getTokenSession().set(SecurityConstants.LOGIN_USER, userInfo);

        return userInfo;
    }
}
